package it.eng.area118.mdocommon.android;

import it.eng.area118.mdocommon.android.log.BasicLogger;
import it.eng.area118.mdocommon.ebus.MessageTextHandler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.OfflineMessageManager;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.MultiUserChat;

import android.util.Log;

public class XmppClientTest {

	private XMPPConnection connection;

	private ArrayList<String> messages = new ArrayList();

	private MessageTextHandler callback = null;

	private MultiUserChat group;

	public XmppClientTest(MessageTextHandler callback) {
		ConnectionConfiguration config = new ConnectionConfiguration("10.0.2.2", 61222);
		connection = new XMPPConnection(config);
		this.callback = callback;
		// TODO: Account Manager non supportato da ActiveMQ
		// try {
		// connection.getAccountManager().createAccount("luigiAccount",
		// "luigiAccount");
		// } catch (XMPPException e) {
		// Log.e("AccountManager", "Error", e);
		// }

	}

	public void available() {
		Presence presence = new Presence(Presence.Type.available);
		connection.sendPacket(presence);
	}

	public void unavailable() {
		Presence presence = new Presence(Presence.Type.unavailable);
		connection.sendPacket(presence);
	}

	public void join() {
		group = new MultiUserChat(this.connection, "roomTest@null");
		try {
			DiscussionHistory history = new DiscussionHistory();
			Calendar now = Calendar.getInstance();
			now.set(Calendar.HOUR_OF_DAY, -1);
			history.setSince(now.getTime());
			group.join("luigi", "luigi", history, 10000);
		}
		catch (XMPPException e) {
			Log.e("Join a Room", "Error while joining", e);
		}

		group.addMessageListener(new PacketListener() {

			@Override
			public void processPacket(Packet packet) {
				Message msg = (Message) packet;
				if (msg != null)
					BasicLogger.writeLog("Message Received!", msg.getBody());
			}
		});

	}

	public void sendGroupMessage(String text) {
		Message msg = group.createMessage();
		msg.setFrom("luigi");
		msg.setSubject("prova");
		msg.setBody(text);
		try {
			group.sendMessage(msg);
		}
		catch (XMPPException e) {
			Log.e("Error", "Errpr", e);
		}
	}

	public void login() {
		try {
			connection.login("luigi", "luigi");
			// connection.loginAnonymously();
		}
		catch (XMPPException e) {
			Log.e("XMPPClient", "Error on login", e);
		}

		PacketFilter filter = new MessageTypeFilter(Type.chat);

		connection.addPacketListener(new PacketListener() {

			@Override
			public void processPacket(Packet packet) {
				BasicLogger.writeLog("addPacketListener", "Packet received: " + packet);
				Message message = (Message) packet;

				String fromName = StringUtils.parseBareAddress(message.getFrom());
				Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
				if (message.getBody() != null) {
					messages.add(fromName + ":" + message.getBody());

					String msgs = "";
					for (String msg : messages) {
						msgs += msg + "\n";
					}
					callback.onSuccess(msgs);
				}
			}
		}

		, filter);

	}

	public void logout() {
		Presence p = new Presence(Presence.Type.unavailable);
		connection.disconnect(p);
	}

	public void disconnect() {
		connection.disconnect();
	}

	public void connect() {
		try {
			connection.connect();
			Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
		}
		catch (XMPPException ex) {
			Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
		}
	}

	public void sendMessage(String text) {
		Log.i("XMPPClient", "Sending text [" + text + "] to [luigi]");
		Message msg = new Message("engineer-8264df", Message.Type.chat);
		msg.setBody(text);
		connection.sendPacket(msg);
	}

	public void getOfflineMessage2() {
		this.connection.createPacketCollector(new PacketFilter() {

			@Override
			public boolean accept(Packet packet) {
				BasicLogger.writeLog("PacketCollector", packet.toString());
				return true;

			}
		});
	}

	public void getOfflineMessage() throws XMPPException {
		OfflineMessageManager offlineMsgManager = new OfflineMessageManager(connection);
		// if (offlineMsgManager.supportsFlexibleRetrieval()) {
		BasicLogger.writeLog("Offline!!", "supportsFlexibleRetrieval: true");
		Iterator<Message> messages = null;
		try {
			messages = offlineMsgManager.getMessages();
		}
		catch (XMPPException e) {
			Log.e("Offline", "While getting offline messages", e);
		}
		if (messages != null) {
			while (messages.hasNext()) {
				Message m = messages.next();
				BasicLogger.writeLog("OfflineXmppClient", m.getBody());
			}
		}
		// } else {
		// BasicLogger.writeLog("Offline!!", "supportsFlexibleRetrieval: false");
		// }

	}
}
